<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="600" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #category="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="15" :md="16" :lg="17" :xl="19">
            <ApiSelect :api="listTableCategory" placeholder="未分类" :params="requestParams" showSearch
              ref="apiSelectRef" :immediate="false"
              @select="(value, opt) => model[field] = value"
              :value="model[field]" optionFilterProp="label" resultField="data" labelField="name"
              valueField="id" />
          </a-col>
          <a-col :sm="9" :md="7" :lg="7" :xl="5">
            <Button type="link" block @click="handleOpenTableCategory"> 管理类型 </Button>
          </a-col>
        </a-row>
      </template>
    </BasicForm>
    <CategoryListModal @register="registerModal" @success="handleCategoryChange"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {Button} from 'ant-design-vue';
import {ApiSelect, BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './table.data';
import {useModal} from '/@/components/Modal';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {listTableCategory, saveOrUpdateTable} from './table.api';
import CategoryListModal from './CategoryListModal.vue';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const rowId = ref('');
const apiSelectRef = ref();
const tenantId = ref(null)
// 必须单独定义个变量, 否则首次请求参数有问题
const requestParams = ref<any>({})
const [registerModal, { openModal }] = useModal();

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 80,
  schemas: formSchema,
  wrapperCol: {
    md: { span: 20 },
    sm: { span: 18 },
  },
  showActionButtonGroup: false,
});


//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  
  isUpdate.value = !!data?.isUpdate;
  tenantId.value = data?.tenantId || data?.record?.tenantId
  setDrawerProps({ confirmLoading: false })

  if (unref(isUpdate)) {
    rowId.value = data.record.id;
  }

  requestParams.value.tenantId = tenantId.value
  await apiSelectRef.value.fetch()
  if (typeof data.record === 'object') {
    setFieldsValue({
      ...data.record,
    })
  }
});

const getTitle = computed(() => isUpdate.value ? '编辑桌台' : '创建桌台');

const handleOpenTableCategory = () => {
  openModal(true, {tenantId: tenantId.value})
}
//提交事件
async function handleSubmit() {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdateTable({ ...values, tenantId: unref(tenantId) }, isUpdate.value);
    closeDrawer();
    emit('success', { values: { ...values, id: rowId.value } });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}

const handleCategoryChange = async () => {
  console.log('handleCategoryChange');
  await apiSelectRef.value.fetch()
}
</script>
